import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const user =  ref(localStorage.getItem('user') && typeof localStorage.getItem('user') == 'string'? JSON.parse(localStorage.getItem('user')) : {})
  const imageObj =  ref(localStorage.getItem('imageObj') && typeof localStorage.getItem('imageObj') == 'string'? JSON.parse(localStorage.getItem('imageObj')) : {})
  const token = ref(localStorage.getItem('token') || '')
  const userRole = ref(localStorage.getItem('userRole') || '')
  const titleName = ref(localStorage.getItem('IndexObjName') || '伟邦人才信息网')
  const route = ref(localStorage.getItem('route') ? JSON.parse(localStorage.getItem('route')) : {})



  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => userRole.value === 'admin')

  function setImageObj(userData) {
    imageObj.value = userData
    localStorage.setItem('imageObj', JSON.stringify(userData))
  }
function setUser(userData) {
  user.value = userData.user
  userRole.value = userData.roles
  localStorage.setItem('userRole', userData.roles)
  localStorage.setItem('user', JSON.stringify(userData.user))
}
  function setToken(userData) {
    token.value = userData.token
    localStorage.setItem('token', userData.token)
  }
function setRoute(userData) {
  route.value = userData.data
  localStorage.setItem('route', JSON.stringify(userData.data))
}


  function logout() {
    user.value = null
    imageObj.value = null
    token.value = ''
    userRole.value = ''
    route.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userRole')
    localStorage.removeItem('user')
    localStorage.removeItem('imageObj')
    localStorage.removeItem('route')
  }

  return {
    user,
    imageObj,
    titleName,
    token,
    route,
    userRole,
    isLoggedIn,
    isAdmin,
    setUser,
    setToken,
    setRoute,
    setImageObj,
    logout
  }
}) 